<template>
    <view class="releaseGood-wrapper">
        <view class="wrapper" v-for="(item, index) of good" :key="item.unid">
            <view class="order-items">
                <view class="wrapper-1">
                    <view class="good-title u-line-2">{{ item.name }}</view>
                </view>
                <view class="wrapper-2">
                    <view class="check-box" @click="setCheckStatus(item)">
                        <text class="icon actived" v-if="item.check">&#xe63d;</text>
                        <text class="icon" v-else>&#xe63f;</text>
                    </view>
                    <view class="model">
                        <view class="u-flex" v-if="item.modelNo">
                            <view class="u-flex-shrink">款号：</view>
                            <view class="bg">{{ item.modelNo }}</view>
                        </view>
                        <view v-if="item.collarName && item.collarName != '无领'">
                            <text>{{ item.collarText }}：</text>
                            <text class="bg" style="letter-spacing: 4rpx">{{ item.collarName }}</text>
                        </view>
                    </view>
                    <view class="order-total">共{{ dealModelTotal(OriginData.sku, item.specificationsCollarId) }}件</view>
                </view>
            </view>
            <view class="skus">
                <template v-for="(itm, idx) in (Object.values(item.children) as Array<any>)">
                    <view class="skus-items-wrapper">
                        <view class="skus-items">
                            <view class="sku-content">
                                <!-- 规格 图 -->
                                <view class="left">
                                    <view class="checkAndImg">
                                        <view style="width: 50rpx"></view>
                                        <view class="image-wrapper" @click="showGoodsDtl(itm)">
                                            <img-cache width="150" height="150" border-radius="10" v-show="itm.picId" class="model-img" :src="itm.picId ? `${global.productImageUrl}${itm.picId}/1` : `/static/images/placeholder.png`" />
                                        </view>
                                    </view>
                                    <view class="sku-content-value">
                                        <view class="colorName">{{ itm.colorName }}</view>
                                        <view class="model-label">({{ itm.modelNo }})</view>
                                        <view class="collarName" v-if="itm.collarName != '无领'">{{ itm.collarName }} </view>
                                        <view class="price">￥{{ itm.userPrice }}</view>
                                    </view>
                                </view>
                                <view class="vertical-line"></view>
                                <!-- 右侧信息 -->
                                <view class="right-part">
                                    <view v-for="(innerItem, i) in itm.list" :key="innerItem.id">
                                        <view class="right-part-line2">
                                            <view class="sub-text">
                                                <text class="skus-items-size">{{ innerItem.sizeName || '空' }}</text>
                                                <view class="o-font-color-black">x{{ innerItem.num }}</view>
                                            </view>
                                            <view>
                                                <uni-number-box v-model="innerItem.refundNum" @change="countchange($event, innerItem)" :max="innerItem.num" :key="'numberBox' + innerItem.id" />
                                            </view>
                                        </view>
                                        <view class="borderBottom"></view>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                </template>
            </view>
            <view class="content-bottom-bar">
                <view class="">
                    <view class="u-flex">
                        <view style="font-size: 28rpx; font-weight: bold">金额：</view>
                        <view class="total-price">￥{{ item.subPrice }}</view>
                    </view>
                    <view class="tips">(不计算优惠)</view>
                </view>
                <view class="u-flex-1 u-text-right o-font-bold">小计 {{ item.subCount }} 件</view>
            </view>
        </view>
    </view>
</template>

<script lang="ts" setup>
import { nextTick, ref } from 'vue'
import global from '@/config'

interface T {
    OriginData: any
    type?: number
}
const Props = withDefaults(defineProps<T>(), {
    OriginData: () => ({}),
    type: 0
})

interface O{
    [key: string]: any
}
const good = ref<O>({})

const emit = defineEmits(['change'])

/** 修改勾选状态 */
function setCheckStatus(item: any) {
    item.check = !item.check
    let id = item.specificationsCollarId
    Props.OriginData.sku.forEach((m: any) => {
        if (m.specificationsCollarId == id) m.refundNum = item.check ? m.num : 0
    })
    countchange()
}

function countchange(e?: any, obj?: any) {
    emit('change')
    // 根据领型分组
    let group = groupBy(Props.OriginData.sku, 'specificationsCollarId')

    nextTick(() => {
        group.forEach(item => {
            let sum = 0,
                price = 0
            let CollarId: string = ''
            item.map((m: any) => {
                sum += m.refundNum
                price += m.refundNum * m.singlePrice
                if (!CollarId) CollarId = m.specificationsCollarId
            })
            good.value[CollarId] = Object.assign(good.value[CollarId], {
                subPrice: Number(price).toFixed(2),
                subCount: sum
            })
        })
    })

    if (obj) {
        let { releaseId, specificationsCollarId } = obj
        // 数量变更之后需要检查是否全部勾选 根据商品id 和 领型id 区分
        let targets = Props.OriginData.sku.filter((m: any) => m.releaseId == releaseId && m.specificationsCollarId == specificationsCollarId)
        // 检查是否每项的退货数量都等于购买数量
        nextTick(() => {
            good.value[specificationsCollarId].check = targets.every((m: any) => m.refundNum == m.num)
        })
    }
}

function groupBy(array: Array<any>, name: string) {
    const groups: { [key: string]: any } = {}
    array.forEach(function (o) {
        const group = JSON.stringify(o[name])
        groups[group] = groups[group] || []
        groups[group].push(o)
    })
    return Object.keys(groups).map(function (group) {
        return groups[group]
    })
}

/**
 * @param {Object} skus 原始的sku 列表
 * @param {Object} id 当前的领型id
 */
function dealModelTotal(skus: Array<any>, id: string) {
    let total = 0
    skus.filter((m: any) => m.specificationsCollarId == id).map((item: any) => {
        total += item.num
    })
    return total
}

function showGoodsDtl({ releaseId }: { releaseId: string }) {
    uni.$u.$MRouter.details.to({ id: releaseId })
}

function dealData() {
    let list = Props.OriginData.sku;

    let _good: {[key:string]: any} = {};

    list.forEach((sku: any) => {
        delete sku.updateTime;
        delete sku.merchantId;

        sku.refundNum = 0;
        let label = sku.specificationsCollarId;
        if (!_good[label]) {
            _good[label] = {};
            _good[label].check = false;
            _good[label].name = sku.goodsName;
            _good[label].collarName = sku.collarName;
            _good[label].modelNo = sku.modelNo;
            _good[label].releaseId = sku.releaseId;
            _good[label].collarText = sku.collarText || "领型";
            _good[label].spuId = sku.spuId;
            _good[label].unid = uni.$u.guid(6);
            _good[label].specificationsCollarId = sku.specificationsCollarId;
            _good[label].subPrice = 0;
            _good[label].subCount = 0;
            _good[label].children = {};
        }
        let temp = _good[label].children;
        if (!temp[sku.colorName]) {
            temp[sku.colorName] = {};
            temp[sku.colorName].picId = sku.picId;
            temp[sku.colorName].userPrice = sku.singlePrice;
            temp[sku.colorName].colorName = sku.colorName;
            temp[sku.colorName].collarName = sku.collarName;
            temp[sku.colorName].modelNo = sku.modelNo;
            temp[sku.colorName].releaseId = sku.releaseId;
            temp[sku.colorName].unid = uni.$u.guid(4);
            temp[sku.colorName].list = [];
        }
        temp[sku.colorName].list.push(sku);
    });
    good.value = _good;
}

dealData()
</script>

<style scoped lang="scss">
@import '../compoments/style.scss';
</style>
